package com.ys.peony.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.shizhefei.view.largeimage.factory.FileBitmapDecoderFactory;
import com.ys.peony.R;
import com.ys.peony.app.BaseApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.yklab.library.refreshlayout.holder.CommonRecyclerViewHolder;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * 图片加载工具类
 * 为方便以后随时更换图片加载库
 * 并且统一配置图片加载方式
 *
 * @author Hunter
 */
public class ImageLoadUtils {

    public static final int DEFAULT_PLACEHOLDER_RESID = R.mipmap.ic_launcher;


    public static void loadImage(Context context, String imageUrl, int resId, ImageView imageView) {
        Glide
                .with(context)
                .load(imageUrl)
                .into(imageView);
    }

    public static void loadImage(Context context, String imageUrl, ImageView imageView) {
        loadImage(context, imageUrl, DEFAULT_PLACEHOLDER_RESID, imageView);
    }

    public static boolean takePicToSave(String filePath, Context context) throws Exception {

        int degree = getBitmapDegree(filePath);
        LogUtil.i("aaaa", "_____degree:" + degree);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        opts.inJustDecodeBounds = false;
        opts.inPurgeable = true;// 允许在内存不足时回收图片
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeFile(filePath, opts);
            //TODO 图片旋转
            if (degree != 0) {
                bitmap = rotateBitmapByDegree(bitmap, degree);
            }
            bitmap = autoFixOrientationByWH(bitmap);
            saveBitmapToFile(filePath, bitmap);

        } catch (OutOfMemoryError error) {
            System.gc();
            return false;
        }
        if (bitmap == null) {
            return false;
        }
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
        return true;
    }

    //压缩
    public static Bitmap compressBySize(String pathName, int targetWidth, int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度；
        float imgWidth = opts.outWidth;
        float imgHeight = opts.outHeight;

        // 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        if (opts.inSampleSize > 3) {
            opts.inSampleSize = 3;
        }
        LogUtil.i("aaaa", "---------opts.inSampleSize-" + opts.inSampleSize);
        // 设置好缩放比例后，加载图片进内容；
        opts.inJustDecodeBounds = false;
//        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        opts.inPurgeable = true;// 允许在内存不足时回收图片
//        opts.inInputShareable = true;
        bitmap = BitmapFactory.decodeFile(pathName, opts);
        return bitmap;
    }


    //旋转
    private static Bitmap autoFixOrientationByWH(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        // 得到图片的宽度、高度；
        float imgWidth = bitmap.getWidth();
        float imgHeight = bitmap.getHeight();
        int angle = 0;
        if (imgWidth > imgHeight) {
            angle = 90;
        }
        LogUtil.i("aaaa", "______angle_" + angle);
        return rotatePic(bitmap, angle);
    }

    public static Bitmap rotatePic(Bitmap source, int angle) {
        Matrix m = new Matrix();
        m.preRotate(angle);
        Bitmap resultBitMap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), m, true);
        return resultBitMap;
    }

    /**
     * 读取图片的旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片的旋转角度
     */
    private static int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
//            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
//            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
//                    ExifInterface.ORIENTATION_FLIP_VERTICAL);
            ExifInterface exif = null;
            if (!StringUtils.isEmpty(path)) {
                exif = new ExifInterface(path);
            } else {
                return 0;
            }
            String rotate = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
            int rotateValue = Integer.parseInt(rotate);
            // 计算旋转角度
            switch (rotateValue) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
                default:
                    degree = 0;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    /**
     * 将bitmap保存到文件中
     *
     * @param filepath
     * @param bitmap
     */
    public static void saveBitmapToFile(String filepath, Bitmap bitmap) {
//        int mHeight = 720 + PixelUtils.dp2px(48);
//        if (bitmap.getHeight() > mHeight) {
//            bitmap = Bitmap.createBitmap(bitmap, 0, PixelUtils.dp2px(48), bitmap.getWidth(), mHeight);
//        }
        if (bitmap == null) {
            return;
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(filepath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
            fOut.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fOut != null) {
                try {
                    fOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }

    }

    /**
     * 将图片的旋转角度置为0
     *
     * @param path
     * @return void
     * @Title: setPictureDegreeZero
     * @date 2012-12-10 上午10:54:46
     */
    public static void setPictureDegreeZero(String path) {
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            //修正图片的旋转角度，设置其不旋转。这里也可以设置其旋转的角度，可以传值过去，
            //例如旋转90度，传值ExifInterface.ORIENTATION_ROTATE_90，需要将这个值转换为String类型的
            exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, "no");
            exifInterface.saveAttributes();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * @param var0:image      absolute path
     * @param imgWidth:image  width
     * @param imgHeight:image height
     * @return
     */
    public static Bitmap decodeScaleImage(String var0, int imgWidth, int imgHeight) {
        if (TextUtils.isEmpty(var0)) {
            return null;
        }
        BitmapFactory.Options var3 = getBitmapOptions(var0);
        int var4 = calculateInSampleSize(var3, imgWidth, imgHeight);
        var3.inSampleSize = var4;
        var3.inJustDecodeBounds = false;
        Bitmap var5 = BitmapFactory.decodeFile(var0, var3);
        int var6 = readPictureDegree(var0);
        Bitmap var7 = null;
        if (var5 != null && var6 != 0) {
            var7 = rotateImageView(var6, var5);
            var5.recycle();
            var5 = null;
            return var7;
        } else {
            return var5;
        }
    }

    public static BitmapFactory.Options getBitmapOptions(String var0) {
        BitmapFactory.Options var1 = new BitmapFactory.Options();
        var1.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(var0, var1);
        return var1;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options, int imageW, int imageH) {
        final int width = options.outWidth;    //图片原始宽度
        final int height = options.outHeight;  //图片原始高度
        int inSampleSize = 1;
        if (width > imageW || height > imageH) {
            final int halfW = width / 2;
            final int halfH = height / 2;
            while (
                    ((halfW / inSampleSize) >= imageW) &&
                            ((halfH / inSampleSize) >= imageH)) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    public static int readPictureDegree(String var0) {
        short var1 = 0;

        try {
            ExifInterface var2 = new ExifInterface(var0);
            int var3 = var2.getAttributeInt("Orientation", 1);
            switch (var3) {
                case 3:
                    var1 = 180;
                    break;
                case 6:
                    var1 = 90;
                    break;
                case 8:
                    var1 = 270;
            }
        } catch (IOException var4) {
            var4.printStackTrace();
        }

        return var1;
    }

    public static Bitmap rotateImageView(int var0, Bitmap var1) {
        Matrix var2 = new Matrix();
        var2.postRotate((float) var0);
        Bitmap var3 = Bitmap.createBitmap(var1, 0, 0, var1.getWidth(), var1.getHeight(), var2, true);
        return var3;
    }

    public static void showImg(ImageView view, String imgUrl) {
        showImg(view, imgUrl, true);
    }

    public static void showImg(ImageView view, String imgUrl, boolean isNeedDiskCache) {
        if (!isNeedDiskCache) {
            Glide.with(BaseApplication.getInstance())
                    .load(imgUrl)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(view);
        } else {
            Glide.with(BaseApplication.getInstance())
                    .load(imgUrl)
                    .into(view);
        }
    }

}
